import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Select,
  Space,
  Typography,
  Tabs,
  Table,
  Tag,
  Progress,
  Statistic,
  Button,
} from "antd";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  LineChart,
  Line,
  PieChart,
  Pie,
  Cell,
} from "recharts";
import {
  UserOutlined,
  BookOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  WarningOutlined,
} from "@ant-design/icons";
import type {
  Student,
  ExamResult,
  StudentPerformance,
  ClassPerformance,
  KnowledgePoint,
} from "./types";
import styled from "styled-components";

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const StatisticCard = styled(Card)`
  .ant-statistic-title {
    font-size: 14px;
  }
  .ant-statistic-content {
    font-size: 24px;
  }
`;

const COLORS = [
  "#1890ff",
  "#52c41a",
  "#faad14",
  "#f5222d",
  "#722ed1",
  "#13c2c2",
];

const LearningAnalysis: React.FC = () => {
  // 状态管理
  const [selectedClass, setSelectedClass] = useState<string>("");
  const [selectedExam, setSelectedExam] = useState<string>("");
  const [classPerformance, setClassPerformance] =
    useState<ClassPerformance | null>(null);
  const [studentPerformances, setStudentPerformances] = useState<
    StudentPerformance[]
  >([]);
  const [loading, setLoading] = useState(false);

  // 模拟数据加载
  useEffect(() => {
    if (selectedClass && selectedExam) {
      setLoading(true);
      // TODO: 替换为实际的API调用
      setTimeout(() => {
        setClassPerformance({
          className: "计算机科学与技术2班",
          studentCount: 45,
          averageScore: 85.5,
          scoreDistribution: [
            { range: "90-100", count: 15 },
            { range: "80-89", count: 20 },
            { range: "70-79", count: 5 },
            { range: "60-69", count: 3 },
            { range: "<60", count: 2 },
          ],
          knowledgePoints: {
            嵌入式基础: {
              averageMastery: 88,
              distribution: [
                { level: "优秀", count: 20 },
                { level: "良好", count: 15 },
                { level: "一般", count: 8 },
                { level: "待加强", count: 2 },
              ],
            },
            操作系统: {
              averageMastery: 82,
              distribution: [
                { level: "优秀", count: 18 },
                { level: "良好", count: 17 },
                { level: "一般", count: 7 },
                { level: "待加强", count: 3 },
              ],
            },
          },
          topStudents: [
            { studentId: "2021001", score: 98 },
            { studentId: "2021002", score: 96 },
            { studentId: "2021003", score: 95 },
          ],
          needHelp: [
            {
              studentId: "2021044",
              weakPoints: ["操作系统", "中断处理"],
              averageScore: 55,
            },
            {
              studentId: "2021045",
              weakPoints: ["任务调度", "设备驱动"],
              averageScore: 58,
            },
          ],
        });
        setLoading(false);
      }, 1000);
    }
  }, [selectedClass, selectedExam]);

  // 渲染成绩分布图表
  const renderScoreDistribution = () => {
    if (!classPerformance) return null;

    return (
      <BarChart
        width={500}
        height={300}
        data={classPerformance.scoreDistribution}
        margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="range" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Bar dataKey="count" name="学生人数" fill="#1890ff" />
      </BarChart>
    );
  };

  // 渲染知识点掌握情况
  const renderKnowledgePoints = () => {
    if (!classPerformance) return null;

    const data = Object.entries(classPerformance.knowledgePoints).map(
      ([name, data]) => ({
        name,
        掌握度: data.averageMastery,
      })
    );

    return (
      <LineChart
        width={500}
        height={300}
        data={data}
        margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="name" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line type="monotone" dataKey="掌握度" stroke="#1890ff" />
      </LineChart>
    );
  };

  return (
    <div>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={8}>
          <Select
            placeholder="选择班级"
            style={{ width: "100%" }}
            value={selectedClass}
            onChange={setSelectedClass}
          >
            <Option value="class1">计算机科学与技术1班</Option>
            <Option value="class2">计算机科学与技术2班</Option>
          </Select>
        </Col>
        <Col span={8}>
          <Select
            placeholder="选择考试"
            style={{ width: "100%" }}
            value={selectedExam}
            onChange={setSelectedExam}
          >
            <Option value="exam1">期中考试</Option>
            <Option value="exam2">期末考试</Option>
          </Select>
        </Col>
      </Row>

      {classPerformance && (
        <>
          <Row gutter={16}>
            <Col span={6}>
              <StatisticCard>
                <Statistic
                  title="班级平均分"
                  value={classPerformance.averageScore}
                  suffix="分"
                  precision={1}
                />
              </StatisticCard>
            </Col>
            <Col span={6}>
              <StatisticCard>
                <Statistic
                  title="及格率"
                  value={
                    ((classPerformance.studentCount -
                      classPerformance.scoreDistribution.find(
                        (item) => item.range === "<60"
                      )?.count!) /
                      classPerformance.studentCount) *
                    100
                  }
                  suffix="%"
                  precision={1}
                />
              </StatisticCard>
            </Col>
            <Col span={6}>
              <StatisticCard>
                <Statistic
                  title="优秀率"
                  value={
                    (classPerformance.scoreDistribution.find(
                      (item) => item.range === "90-100"
                    )?.count! /
                      classPerformance.studentCount) *
                    100
                  }
                  suffix="%"
                  precision={1}
                />
              </StatisticCard>
            </Col>
            <Col span={6}>
              <StatisticCard>
                <Statistic
                  title="参考人数"
                  value={classPerformance.studentCount}
                />
              </StatisticCard>
            </Col>
          </Row>

          <Row gutter={16} style={{ marginTop: 24 }}>
            <Col span={12}>
              <StyledCard title="成绩分布">
                {renderScoreDistribution()}
              </StyledCard>
            </Col>
            <Col span={12}>
              <StyledCard title="知识点掌握情况">
                {renderKnowledgePoints()}
              </StyledCard>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <StyledCard
                title="优秀学生"
                extra={<Button type="link">查看全部</Button>}
              >
                <Table
                  dataSource={classPerformance.topStudents}
                  columns={[
                    {
                      title: "学号",
                      dataIndex: "studentId",
                      key: "studentId",
                    },
                    {
                      title: "得分",
                      dataIndex: "score",
                      key: "score",
                      render: (score: number) => (
                        <Tag color="success">{score}分</Tag>
                      ),
                    },
                  ]}
                  pagination={false}
                />
              </StyledCard>
            </Col>
            <Col span={12}>
              <StyledCard
                title="需要帮助的学生"
                extra={<Button type="link">查看全部</Button>}
              >
                <Table
                  dataSource={classPerformance.needHelp}
                  columns={[
                    {
                      title: "学号",
                      dataIndex: "studentId",
                      key: "studentId",
                    },
                    {
                      title: "平均分",
                      dataIndex: "averageScore",
                      key: "averageScore",
                      render: (score: number) => (
                        <Tag color="error">{score}分</Tag>
                      ),
                    },
                    {
                      title: "薄弱知识点",
                      dataIndex: "weakPoints",
                      key: "weakPoints",
                      render: (points: string[]) => (
                        <Space size={[0, 4]} wrap>
                          {points.map((point) => (
                            <Tag key={point} color="warning">
                              {point}
                            </Tag>
                          ))}
                        </Space>
                      ),
                    },
                  ]}
                  pagination={false}
                />
              </StyledCard>
            </Col>
          </Row>
        </>
      )}
    </div>
  );
};

export default LearningAnalysis;
